<template>
  <div class="card">
    <dv-border-box-13 title="线索汇聚" :color="['#168BF9', '#112F7C']">
      <!-- 添加标题组件 -->
      <CardTitle
        title="线索汇聚"
        :show-detail="true"
        @detail-click="handleDetail"
      />
      <div class="content-wrapper">
        <!-- 图表区域 - 垂直排列 -->
        <div class="charts-container">
          <!-- 类型分析环形图 -->
          <div class="chart-item vertical-item">
            <div class="chart-title">类型分析</div>
            <div class="chart-container">
              <div ref="typeChart" class="chart"></div>
              <div class="chart-center">
                <div class="total-text">总计</div>
                <div class="total-number">{{ totalCount }}</div>
              </div>
            </div>
          </div>

          <!-- 线索报送量柱状图 -->
          <div class="chart-item vertical-item">
            <div class="chart-header">
              <div class="chart-title">线索报送量</div>
              <div class="tab-switch">
                <el-radio-group
                  v-model="reportTab"
                  size="mini"
                  @change="handleReportTabChange"
                >
                  <el-radio-button label="区县">区县</el-radio-button>
                  <el-radio-button label="部门">部门</el-radio-button>
                </el-radio-group>
              </div>
            </div>
            <div class="chart-container">
              <div ref="reportChart" class="chart"></div>
            </div>
          </div>
        </div>
      </div>
    </dv-border-box-13>
  </div>
</template>

<script>
import * as echarts from "echarts";
import CardTitle from "../components/card-title.vue"; // 引入标题组件
import { currentPOST } from "api/modules";

export default {
  name: "ClueAnalysis",
  components: {
    CardTitle,
  },
  data() {
    return {
      reportTab: "区县", // 报送量图表tab
      totalCount: 0, // 总数量
      typeData: [], // 类型数据
      districtData: [], // 区县数据
      departmentData: [], // 部门数据
      lastDay: 30, // 默认查询最近30天
    };
  },
  watch: {
    // 监听 lastDay 的变化，当变化时重新获取数据
    lastDay: {
      handler(newVal) {
        this.refreshData();
      },
      immediate: true, // 立即执行一次
    },
  },
  mounted() {
    // 监听窗口大小变化
    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.typeChart) {
      this.typeChart.dispose();
    }
    if (this.reportChart) {
      this.reportChart.dispose();
    }
    // 移除事件监听
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    // 刷新所有数据
    refreshData() {
      this.getTypeData();
      this.getReportData();
    },

    // 获取类型数据
    getTypeData() {
      currentPOST("leftTopIndustryPieClues", {
        lastDay: this.lastDay,
      })
        .then((res) => {
          if (res.code === 0) {
            // 转换数据格式：{industry: "未分类", count: "10"} -> {name: "未分类", value: 10}
            this.typeData = res.data.map((item) => ({
              name: item.industry,
              value: parseInt(item.count),
            }));

            // 计算总数
            this.totalCount = this.typeData.reduce(
              (sum, item) => sum + item.value,
              0
            );

            // 重新渲染图表
            if (this.typeChart) {
              this.initTypeChart();
            } else {
              this.$nextTick(() => {
                this.initTypeChart();
              });
            }
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          // 这里加上圆括号
          console.error("类型数据请求失败:", error);
        });
    },

    // 获取报送量数据
    getReportData() {
      // 显示加载状态
      if (this.reportChart) {
        this.reportChart.showLoading({
          text: "加载中...",
          color: "#1890ff",
          textColor: "#bae7ff",
          maskColor: "rgba(5, 64, 128, 0.3)",
        });
      }

      currentPOST("leftTopOrganizationNamePieClues", {
        lastDay: this.lastDay,
        createdOrganizationType: this.reportTab,
      })
        .then((res) => {
          // 隐藏加载状态
          if (this.reportChart) {
            this.reportChart.hideLoading();
          }

          if (res.code === 0) {
            // 转换数据格式：{organizationName: "融媒体中心", count: "10"} -> {name: "融媒体中心", value: 10}
            const reportData = res.data.map((item) => ({
              name: item.organizationName,
              value: parseInt(item.count),
            }));

            // 根据tab类型存储数据
            if (this.reportTab === "区县") {
              this.districtData = reportData;
            } else {
              this.departmentData = reportData;
            }

            // 重新渲染图表
            this.$nextTick(() => {
              this.initReportChart();
            });
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          // 隐藏加载状态
          if (this.reportChart) {
            this.reportChart.hideLoading();
          }
          console.error("报送量数据请求失败:", error);
        });
    },

    // 初始化类型分析环形图
    initTypeChart() {
      if (!this.$refs.typeChart) return;

      this.typeChart = echarts.init(this.$refs.typeChart);
      const option = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        legend: {
          orient: "vertical",
          right: 10,
          top: "center",
          textStyle: {
            color: "#bae7ff",
            fontSize: 12,
          },
          itemWidth: 12,
          itemHeight: 12,
        },
        series: [
          {
            name: "线索类型",
            type: "pie",
            radius: ["50%", "70%"],
            center: ["40%", "50%"],
            avoidLabelOverlap: false,
            itemStyle: {
              borderColor: "#0a2c5e",
              borderWidth: 2,
            },
            // 添加标签和连接线
            label: {
              show: true,
              position: "outside",
              formatter: "{b}: {c} ({d}%)",
              color: "#bae7ff",
              fontSize: 12,
            },
            labelLine: {
              show: true,
              length: 10, // 第一段线长度
              length2: 15, // 第二段线长度
              lineStyle: {
                color: "rgba(186, 231, 255, 0.6)", // 细线颜色
                width: 1, // 细线宽度
              },
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "14",
                fontWeight: "bold",
              },
            },
            data: this.typeData.map((item) => ({
              ...item,
              itemStyle: {
                color: this.getTypeColor(item.name),
              },
            })),
          },
        ],
      };
      this.typeChart.setOption(option);
    },

    // 初始化报送量柱状图 - 立体圆柱形
    initReportChart() {
      if (!this.$refs.reportChart) return;

      // 每次重新初始化图表实例
      if (this.reportChart) {
        this.reportChart.dispose();
      }
      this.reportChart = echarts.init(this.$refs.reportChart);

      const data =
        this.reportTab === "区县" ? this.districtData : this.departmentData;

      // 如果没有数据，显示空状态
      if (!data || data.length === 0) {
        const option = {
          title: {
            text: "暂无数据",
            textStyle: {
              color: "#bae7ff",
              fontSize: 14,
            },
            left: "center",
            top: "center",
          },
        };
        this.reportChart.setOption(option);
        return;
      }

      // 创建圆柱形渐变效果
      const createCylinderGradient = (value, maxValue) => {
        return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: "#36a3ff" }, // 顶部亮色
          { offset: 0.3, color: "#1890ff" }, // 主体颜色
          { offset: 0.7, color: "#096dd9" }, // 底部暗色
          { offset: 1, color: "#0050b3" }, // 最底部
        ]);
      };

      const maxValue = Math.max(...data.map((item) => item.value));

      const option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
          formatter: function (params) {
            return `${params[0].name}<br/>报送量: ${params[0].value}`;
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "15%",
          top: "15%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: data.map((item) => item.name),
          axisLabel: {
            color: "#bae7ff",
            fontSize: 12,
            interval: 0,
            rotate: 0, // 改为0度，平放显示
          },
          axisLine: {
            lineStyle: {
              color: "#2d5278",
            },
          },
          axisTick: {
            show: false,
          },
        },
        yAxis: {
          type: "value",
          axisLabel: {
            color: "#bae7ff",
            fontSize: 12,
          },
          axisLine: {
            lineStyle: {
              color: "#2d5278",
            },
          },
          splitLine: {
            lineStyle: {
              color: "rgba(45, 82, 120, 0.3)",
              type: "dashed",
            },
          },
        },
        series: [
          {
            name: "报送量",
            type: "bar",
            barWidth: "35%", // 调整宽度以适应圆柱效果
            roundCap: true, // 圆柱顶部圆角
            itemStyle: {
              color: function (params) {
                return createCylinderGradient(params.value, maxValue);
              },
              // 添加阴影效果增强立体感
              shadowBlur: 10,
              shadowColor: "rgba(24, 144, 255, 0.5)",
              // 添加边框增强立体感
              borderWidth: 0,
              borderRadius: [8, 8, 0, 0], // 顶部圆角，底部直角
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 20,
                shadowColor: "rgba(24, 144, 255, 0.8)",
              },
            },
            data: data.map((item) => ({
              value: item.value,
              name: item.name,
            })),
            label: {
              show: true,
              position: "top",
              color: "#ffffff",
              fontSize: 12,
              fontWeight: "bold",
              formatter: "{c}",
            },
          },
          // 添加底部阴影效果
          {
            type: "pictorialBar",
            symbol: "rect",
            symbolSize: ["35%", 4],
            symbolOffset: [0, 2],
            z: -1,
            itemStyle: {
              color: "rgba(24, 144, 255, 0.3)",
            },
            data: data.map((item) => item.value),
          },
        ],
      };
      this.reportChart.setOption(option);
    },

    // 获取类型颜色
    getTypeColor(type) {
      const colors = {
        三农: "#52c41a",
        财经: "#faad14",
        时政: "#f5222d",
        社会: "#722ed1",
        未分类: "#13c2c2",
        其他: "#1890ff",
      };
      return colors[type] || this.generateColor(type);
    },

    // 为未知类型生成随机颜色
    generateColor(type) {
      const colors = [
        "#1890ff",
        "#52c41a",
        "#faad14",
        "#f5222d",
        "#722ed1",
        "#13c2c2",
        "#eb2f96",
        "#fa541c",
        "#a0d911",
        "#2f54eb",
      ];
      // 根据类型名称生成一个稳定的索引
      let hash = 0;
      for (let i = 0; i < type.length; i++) {
        hash = type.charCodeAt(i) + ((hash << 5) - hash);
      }
      return colors[Math.abs(hash) % colors.length];
    },

    // 报送量tab切换
    handleReportTabChange() {
      // 直接重新请求数据，不需要手动清空数据
      this.getReportData();
    },

    // 处理详情点击
    handleDetail() {
      // 处理详情点击逻辑
      console.log("详情点击");
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.typeChart) {
        this.typeChart.resize();
      }
      if (this.reportChart) {
        this.reportChart.resize();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.card {
  margin-top: 30px;
  height: 550px;
  display: flex;
  justify-content: center;
}

.content-wrapper {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
  margin-top: -30px;
}

// 图表容器 - 垂直排列
.charts-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 15px;
  height: 460px;
}

.chart-item {
  background: rgba(5, 64, 128, 0.2);
  border-radius: 8px;
  padding: 12px;
  box-sizing: border-box;
  position: relative;

  // 垂直排列的项
  &.vertical-item {
    flex: 1;
    min-height: 180px;
    display: flex;
    flex-direction: column;
  }

  .chart-title {
    color: #bae7ff;
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 10px;
    flex-shrink: 0;
  }

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
    flex-shrink: 0;

    .tab-switch {
      ::v-deep .el-radio-group {
        .el-radio-button {
          .el-radio-button__inner {
            background: rgba(5, 64, 128, 0.5);
            color: #bae7ff;
            border: 1px solid #2d5278;
            font-size: 12px;
            padding: 5px 10px;

            &:hover {
              color: #ffffff;
              background: rgba(45, 82, 120, 0.8);
            }
          }

          &.is-active {
            .el-radio-button__inner {
              background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
              color: #ffffff;
              border-color: #1890ff;
            }
          }
        }
      }
    }
  }

  .chart-container {
    position: relative;
    width: 100%;
    flex: 1;
    min-height: 150px;

    .chart {
      width: 100%;
      height: 170px;
    }

    .chart-center {
      position: absolute;
      top: 50%;
      left: 40%;
      transform: translate(-50%, -50%);
      text-align: center;

      .total-text {
        color: #bae7ff;
        font-size: 14px;
        margin-bottom: 5px;
      }

      .total-number {
        color: #ffffff;
        font-size: 24px;
        font-weight: bold;
        text-shadow: 0 0 10px rgba(24, 144, 255, 0.8);
      }
    }
  }
}


</style>
